﻿#include <iostream>
#include<boost/asio.hpp>
using namespace boost::asio::ip;
const int MAX_LENGTH = 1024;
int main()
{
    try {
        boost::asio::io_context ioc;    //创建上下文服务

        tcp::endpoint remote_ep(address::from_string("127.0.0.1"), 10086);//对端的地址和端口

        tcp::socket sock(ioc);//第二个参数可写可不写，第二个是对端的协议

        boost::system::error_code error = boost::asio::error::host_not_found;   //错误码

        sock.connect(remote_ep, error); //连接结果会在error错误码显示

        if (error) {
            std::cout << "connect failed , code is " << error.value() << "error message is " << error.message() << std::endl;
        }

        //客户端write给服务端
        std::cout << "Enter message:";
        
        char request[MAX_LENGTH];

        std::cin.getline(request, MAX_LENGTH);  //输入要发送的数据

        size_t request_length=strlen(request);//获取发送长度

        boost::asio::write(sock, boost::asio::buffer(request, request_length));//通过write全部发出到服务器

        //客户端read来自服务的的
        char reply[MAX_LENGTH];     //通过reply接收服务器发送的数据

        size_t reply_length = boost::asio::read(sock,boost::asio::buffer(reply, request_length));

       
        std::cout << "Reply is: ";

        std::cout.write(reply, reply_length);   //输出内容 
        std::cout << "\n";
    }
    catch(std::exception &e){
        std::cerr << "Exception: " << e.what() << std::endl;
    }
    return 0;
}

